#include <fstream>
#include "headfiles.h"


using namespace std;

int main(int argc, char **argv) {
    if (argc != 2) {
        cout << "Usage: " << argv[0] << " input_file" << endl;
        return 0;
    }

    string file_name(argv[1]);
    fstream fs;
    fs.open(file_name.c_str(), fstream::in);
    if (!fs.is_open()) {
        cout << "File " << file_name << " open error!" << endl;
        return 1;
    }

    //In the file, the first two numbers are the x and y ranges.
    int i, range[2];
    string str;

    // Read the two ranges
    for (i = 0; i < 2; i++) {
        fs >> str;
        if (str.empty()) {
            return 1;
        }

        int tmp = atoi(str.c_str());
        if (tmp <= 0) {
            cout << "Range value " << i << " is error, " << tmp << "!" << endl;
        }
        range[i] = tmp;
    }

    // Allocate the area array
    COLOR *area = (COLOR *)malloc(sizeof(COLOR) * range[0] * range[1]);
    if (area == NULL) {
        cout << "Allocate area pointer error, NULL!" << endl;
        return 1;
    }

    int loc = 0;
    while (fs >> str) {
        if (str.empty()) {
            break;
        }

        int tmp = atoi(str.c_str());
        area[loc++] = static_cast<COLOR>(tmp);
    }
    fs.close();

    if (loc != range[0] * range[1]) {
        cout << "Input area is not fully filled!" << endl;
        return 1;
    }

    // Before paint
    cout << "Before paint:" << endl;
    printArea(area, range[0], range[1]);

    paintFill(area, 3, 3, BLACK, YELLOW, range[0], range[1]);

    // After paint
    cout << "After paint:" << endl;
    printArea(area, range[0], range[1]);
    free(area);
}
